<template>
  <div class="resources-view">
    <!-- 资源概览 -->
    <div class="resources-overview">
      <div class="overview-header">
        <h2>资源管理</h2>
        <div class="overview-actions">
          <button class="action-btn" @click="toggleAutoTrade">
            <span class="btn-icon">🔄</span>
            {{ autoTradeEnabled ? '关闭自动交易' : '开启自动交易' }}
          </button>
          <button class="action-btn" @click="openMarket">
            <span class="btn-icon">🏪</span>
            市场交易
          </button>
        </div>
      </div>
      
      <div class="resources-grid">
        <ResourceCard
          v-for="resource in mainResources"
          :key="resource.id"
          :resource="resource"
          @upgrade-storage="upgradeStorage"
          @trade="openTradeModal"
        />
      </div>
    </div>

    <!-- 生产详情 -->
    <div class="production-section">
      <div class="section-header">
        <h3>生产详情</h3>
        <div class="production-controls">
          <button 
            class="filter-btn"
            :class="{ active: productionFilter === 'all' }"
            @click="productionFilter = 'all'"
          >
            全部
          </button>
          <button 
            class="filter-btn"
            :class="{ active: productionFilter === 'positive' }"
            @click="productionFilter = 'positive'"
          >
            正产出
          </button>
          <button 
            class="filter-btn"
            :class="{ active: productionFilter === 'negative' }"
            @click="productionFilter = 'negative'"
          >
            负产出
          </button>
        </div>
      </div>
      
      <div class="production-list">
        <div 
          v-for="item in filteredProduction" 
          :key="item.resource"
          class="production-item"
          :class="{ 
            positive: item.production > 0, 
            negative: item.production < 0,
            neutral: item.production === 0
          }"
        >
          <div class="production-info">
            <div class="resource-icon">{{ getResourceIcon(item.resource) }}</div>
            <div class="resource-details">
              <div class="resource-name">{{ getResourceName(item.resource) }}</div>
              <div class="resource-sources">
                <span 
                  v-for="source in item.sources" 
                  :key="source.name"
                  class="source-tag"
                >
                  {{ source.name }}: {{ formatNumber(source.amount) }}
                </span>
              </div>
            </div>
          </div>
          <div class="production-amount" :class="getProductionClass(item.production)">
            {{ formatProduction(item.production) }}
          </div>
        </div>
      </div>
    </div>

    <!-- 存储设施 -->
    <div class="storage-section">
      <div class="section-header">
        <h3>存储设施</h3>
        <button class="action-btn secondary" @click="planStorage">
          <span class="btn-icon">📋</span>
          存储规划
        </button>
      </div>
      
      <div class="storage-grid">
        <div 
          v-for="storage in storageInfo" 
          :key="storage.resource"
          class="storage-item"
        >
          <div class="storage-header">
            <div class="storage-icon">{{ getResourceIcon(storage.resource) }}</div>
            <div class="storage-name">{{ getResourceName(storage.resource) }}仓库</div>
            <div class="storage-level">等级 {{ storage.level }}</div>
          </div>
          
          <div class="storage-bar">
            <div class="storage-progress">
              <div 
                class="storage-fill" 
                :style="{ width: `${storage.utilization}%` }"
                :class="getStorageClass(storage.utilization)"
              ></div>
            </div>
            <div class="storage-text">
              {{ formatNumber(storage.current) }} / {{ formatNumber(storage.capacity) }}
            </div>
          </div>
          
          <div class="storage-actions">
            <button 
              class="upgrade-btn"
              :disabled="!canUpgradeStorage(storage.resource)"
              @click="upgradeStorage(storage.resource)"
            >
              升级 ({{ getUpgradeCost(storage.resource) }})
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 市场价格 -->
    <div class="market-section">
      <div class="section-header">
        <h3>市场价格</h3>
        <div class="market-info">
          <span class="market-status">市场状态: 正常</span>
          <span class="last-update">最后更新: {{ formatTime(lastMarketUpdate) }}</span>
        </div>
      </div>
      
      <div class="market-grid">
        <div 
          v-for="price in marketPrices" 
          :key="price.resource"
          class="market-item"
        >
          <div class="market-resource">
            <div class="resource-icon">{{ getResourceIcon(price.resource) }}</div>
            <div class="resource-name">{{ getResourceName(price.resource) }}</div>
          </div>
          
          <div class="market-prices">
            <div class="buy-price">
              <span class="price-label">买入:</span>
              <span class="price-value">{{ price.buyPrice }}</span>
              <span class="price-trend" :class="price.buyTrend">
                {{ getTrendIcon(price.buyTrend) }}
              </span>
            </div>
            <div class="sell-price">
              <span class="price-label">卖出:</span>
              <span class="price-value">{{ price.sellPrice }}</span>
              <span class="price-trend" :class="price.sellTrend">
                {{ getTrendIcon(price.sellTrend) }}
              </span>
            </div>
          </div>
          
          <div class="market-actions">
            <button class="trade-btn buy" @click="quickTrade(price.resource, 'buy')">
              快速买入
            </button>
            <button class="trade-btn sell" @click="quickTrade(price.resource, 'sell')">
              快速卖出
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 交易模态框 -->
    <TradeModal
      v-if="showTradeModal"
      :resource="selectedResource"
      @close="closeTradeModal"
      @trade="executeTrade"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { useResourcesStore, useBuildingsStore } from '@/stores'
import ResourceCard from '@/components/ui/ResourceCard.vue'
import TradeModal from '@/components/ui/TradeModal.vue'

const resourcesStore = useResourcesStore()
const buildingsStore = useBuildingsStore()

// 响应式数据
const productionFilter = ref<'all' | 'positive' | 'negative'>('all')
const autoTradeEnabled = ref(false)
const showTradeModal = ref(false)
const selectedResource = ref('')
const lastMarketUpdate = ref(Date.now())

// 计算属性
const mainResources = computed(() => {
  const resources = ['energy', 'metals', 'crystals', 'rare_metals', 'credits', 'research_points', 'influence']
  return resources.map(id => ({
    id,
    name: getResourceName(id),
    icon: getResourceIcon(id),
    amount: resourcesStore.resources[id] || 0,
    production: resourcesStore.getResourceProduction(id),
    storage: resourcesStore.getResourceStorage(id),
    utilization: ((resourcesStore.resources[id] || 0) / resourcesStore.getResourceStorage(id)) * 100
  }))
})

const filteredProduction = computed(() => {
  const production = Object.entries(resourcesStore.production).map(([resource, amount]) => ({
    resource,
    production: amount,
    sources: getProductionSources(resource)
  }))

  switch (productionFilter.value) {
    case 'positive':
      return production.filter(item => item.production > 0)
    case 'negative':
      return production.filter(item => item.production < 0)
    default:
      return production
  }
})

const storageInfo = computed(() => {
  const resources = ['energy', 'metals', 'crystals', 'rare_metals', 'credits']
  return resources.map(resource => ({
    resource,
    level: getStorageLevel(resource),
    current: resourcesStore.resources[resource] || 0,
    capacity: resourcesStore.getResourceStorage(resource),
    utilization: ((resourcesStore.resources[resource] || 0) / resourcesStore.getResourceStorage(resource)) * 100
  }))
})

const marketPrices = computed(() => {
  const resources = ['energy', 'metals', 'crystals', 'rare_metals']
  return resources.map(resource => ({
    resource,
    buyPrice: resourcesStore.getMarketPrice(resource, 'buy'),
    sellPrice: resourcesStore.getMarketPrice(resource, 'sell'),
    buyTrend: getRandomTrend(),
    sellTrend: getRandomTrend()
  }))
})

// 方法
function getResourceName(resourceId: string): string {
  const names: Record<string, string> = {
    energy: '能量',
    metals: '金属',
    crystals: '水晶',
    rare_metals: '稀有金属',
    credits: '信用点',
    research_points: '研究点',
    influence: '影响力'
  }
  return names[resourceId] || resourceId
}

function getResourceIcon(resourceId: string): string {
  const icons: Record<string, string> = {
    energy: '⚡',
    metals: '🔩',
    crystals: '💎',
    rare_metals: '🌟',
    credits: '💰',
    research_points: '🔬',
    influence: '👑'
  }
  return icons[resourceId] || '❓'
}

function formatNumber(num: number): string {
  if (num >= 1000000000) {
    return (num / 1000000000).toFixed(1) + 'B'
  } else if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  } else {
    return Math.floor(num).toString()
  }
}

function formatProduction(amount: number): string {
  const sign = amount >= 0 ? '+' : ''
  return `${sign}${formatNumber(amount)}/分钟`
}

function formatTime(timestamp: number): string {
  const now = Date.now()
  const diff = now - timestamp
  const minutes = Math.floor(diff / 60000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  
  const hours = Math.floor(minutes / 60)
  return `${hours}小时前`
}

function getProductionClass(production: number): string {
  if (production > 0) return 'positive'
  if (production < 0) return 'negative'
  return 'neutral'
}

function getStorageClass(utilization: number): string {
  if (utilization >= 90) return 'critical'
  if (utilization >= 75) return 'warning'
  return 'normal'
}

function getProductionSources(resource: string) {
  // 模拟生产来源
  const sources = [
    { name: '基础设施', amount: Math.random() * 100 },
    { name: '工业建筑', amount: Math.random() * 200 },
    { name: '研究设施', amount: Math.random() * 50 }
  ]
  return sources.filter(s => s.amount > 0)
}

function getStorageLevel(resource: string): number {
  // 模拟存储等级
  return Math.floor(Math.random() * 5) + 1
}

function getUpgradeCost(resource: string): string {
  // 模拟升级成本
  return `${Math.floor(Math.random() * 1000) + 500} 金属`
}

function canUpgradeStorage(resource: string): boolean {
  // 模拟是否可以升级
  return resourcesStore.resources.metals >= 500
}

function getRandomTrend(): 'up' | 'down' | 'stable' {
  const trends = ['up', 'down', 'stable']
  return trends[Math.floor(Math.random() * trends.length)] as 'up' | 'down' | 'stable'
}

function getTrendIcon(trend: string): string {
  const icons = {
    up: '↗️',
    down: '↘️',
    stable: '→'
  }
  return icons[trend as keyof typeof icons] || '→'
}

// 事件处理
function toggleAutoTrade() {
  autoTradeEnabled.value = !autoTradeEnabled.value
}

function openMarket() {
  // 打开市场界面
  console.log('打开市场界面')
}

function upgradeStorage(resource: string) {
  if (canUpgradeStorage(resource)) {
    resourcesStore.removeResource('metals', 500)
    // 这里应该调用升级存储的逻辑
    console.log(`升级${resource}存储`)
  }
}

function openTradeModal(resource: string) {
  selectedResource.value = resource
  showTradeModal.value = true
}

function closeTradeModal() {
  showTradeModal.value = false
  selectedResource.value = ''
}

function executeTrade(data: { resource: string; amount: number; type: 'buy' | 'sell' }) {
  // 执行交易逻辑
  console.log('执行交易:', data)
  closeTradeModal()
}

function planStorage() {
  // 打开存储规划界面
  console.log('打开存储规划界面')
}

function quickTrade(resource: string, type: 'buy' | 'sell') {
  // 快速交易
  const amount = 100
  if (type === 'buy') {
    const cost = amount * resourcesStore.getMarketPrice(resource, 'buy')
    if (resourcesStore.resources.credits >= cost) {
      resourcesStore.removeResource('credits', cost)
      resourcesStore.addResource(resource, amount)
    }
  } else {
    if (resourcesStore.resources[resource] >= amount) {
      resourcesStore.removeResource(resource, amount)
      const income = amount * resourcesStore.getMarketPrice(resource, 'sell')
      resourcesStore.addResource('credits', income)
    }
  }
}
</script>

<style scoped>
.resources-view {
  padding: 1rem;
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.overview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.overview-header h2 {
  margin: 0;
  color: #ffffff;
  font-size: 1.5rem;
}

.overview-actions {
  display: flex;
  gap: 0.5rem;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: #00d4ff;
  color: #000000;
  border: none;
  border-radius: 6px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.action-btn:hover {
  background: #0099cc;
  transform: translateY(-1px);
}

.action-btn.secondary {
  background: rgba(255, 255, 255, 0.1);
  color: #ffffff;
}

.action-btn.secondary:hover {
  background: rgba(255, 255, 255, 0.2);
}

.btn-icon {
  font-size: 1rem;
}

.resources-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 1rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1rem;
}

.section-header h3 {
  margin: 0;
  color: #00d4ff;
  font-size: 1.2rem;
}

.production-controls {
  display: flex;
  gap: 0.25rem;
}

.filter-btn {
  padding: 0.25rem 0.75rem;
  background: rgba(255, 255, 255, 0.1);
  color: #cccccc;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.filter-btn.active {
  background: #00d4ff;
  color: #000000;
}

.production-list {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.production-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.75rem;
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  border-left: 3px solid #666666;
}

.production-item.positive {
  border-left-color: #00ff88;
}

.production-item.negative {
  border-left-color: #ff4444;
}

.production-info {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  flex: 1;
}

.resource-icon {
  font-size: 1.5rem;
  min-width: 24px;
}

.resource-details {
  flex: 1;
}

.resource-name {
  font-weight: 500;
  color: #ffffff;
  margin-bottom: 0.25rem;
}

.resource-sources {
  display: flex;
  gap: 0.5rem;
  flex-wrap: wrap;
}

.source-tag {
  font-size: 0.75rem;
  color: #888888;
  background: rgba(255, 255, 255, 0.05);
  padding: 0.125rem 0.375rem;
  border-radius: 3px;
}

.production-amount {
  font-weight: bold;
  font-size: 1rem;
}

.production-amount.positive {
  color: #00ff88;
}

.production-amount.negative {
  color: #ff4444;
}

.production-amount.neutral {
  color: #888888;
}

.storage-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1rem;
}

.storage-item {
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 1rem;
}

.storage-header {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.storage-icon {
  font-size: 1.2rem;
}

.storage-name {
  flex: 1;
  font-weight: 500;
  color: #ffffff;
}

.storage-level {
  font-size: 0.875rem;
  color: #00d4ff;
  background: rgba(0, 212, 255, 0.1);
  padding: 0.125rem 0.5rem;
  border-radius: 4px;
}

.storage-bar {
  margin-bottom: 0.75rem;
}

.storage-progress {
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 0.25rem;
}

.storage-fill {
  height: 100%;
  transition: width 0.3s ease;
}

.storage-fill.normal {
  background: linear-gradient(90deg, #00d4ff, #0099cc);
}

.storage-fill.warning {
  background: linear-gradient(90deg, #f59e0b, #d97706);
}

.storage-fill.critical {
  background: linear-gradient(90deg, #ef4444, #dc2626);
}

.storage-text {
  font-size: 0.875rem;
  color: #cccccc;
  text-align: center;
}

.storage-actions {
  text-align: center;
}

.upgrade-btn {
  padding: 0.375rem 0.75rem;
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
  border: 1px solid #00d4ff;
  border-radius: 4px;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upgrade-btn:hover:not(:disabled) {
  background: #00d4ff;
  color: #000000;
}

.upgrade-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.market-info {
  display: flex;
  gap: 1rem;
  font-size: 0.875rem;
  color: #888888;
}

.market-status {
  color: #00ff88;
}

.market-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(320px, 1fr));
  gap: 1rem;
}

.market-item {
  background: rgba(0, 0, 0, 0.4);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  padding: 1rem;
}

.market-resource {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  margin-bottom: 0.75rem;
}

.market-prices {
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.75rem;
}

.buy-price,
.sell-price {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.25rem;
}

.price-label {
  font-size: 0.75rem;
  color: #888888;
}

.price-value {
  font-weight: bold;
  color: #ffffff;
}

.price-trend {
  font-size: 0.875rem;
}

.price-trend.up {
  color: #00ff88;
}

.price-trend.down {
  color: #ff4444;
}

.price-trend.stable {
  color: #888888;
}

.market-actions {
  display: flex;
  gap: 0.5rem;
}

.trade-btn {
  flex: 1;
  padding: 0.375rem 0.75rem;
  border: none;
  border-radius: 4px;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
}

.trade-btn.buy {
  background: rgba(0, 255, 136, 0.2);
  color: #00ff88;
  border: 1px solid #00ff88;
}

.trade-btn.buy:hover {
  background: #00ff88;
  color: #000000;
}

.trade-btn.sell {
  background: rgba(255, 68, 68, 0.2);
  color: #ff4444;
  border: 1px solid #ff4444;
}

.trade-btn.sell:hover {
  background: #ff4444;
  color: #ffffff;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .resources-grid {
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  }
  
  .storage-grid,
  .market-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .resources-view {
    padding: 0.5rem;
    gap: 1rem;
  }
  
  .overview-header {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }
  
  .overview-actions {
    justify-content: center;
  }
  
  .section-header {
    flex-direction: column;
    align-items: stretch;
    gap: 0.5rem;
  }
  
  .production-controls {
    justify-content: center;
  }
  
  .market-info {
    flex-direction: column;
    gap: 0.25rem;
  }
}
</style>